package com.wfx.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.wfx.entity.Result;
import com.wfx.entity.WxbOrder;
import com.wfx.service.IPayService;
import com.wfx.service.IWxbOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>title: com.wfx.pay</p>
 * author zhuximing
 * description:
 */
@RestController
@RequestMapping("/weixin")
@CrossOrigin
public class WxPayController {
    @Autowired
    private IPayService payService;


    @Autowired
    private IWxbOrderService iWxbOrderService;


    @RequestMapping("unifiedorder")
    public Result unifiedorder(String orderId){
        System.out.println(orderId);
        return payService.pay(orderId) ;
    }
    
    
    @RequestMapping("notify")
    public String  notify(HttpServletRequest request) throws  Exception{
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = inStream.read(buffer)) != -1){
            outSteam.write(buffer,0,len);
        }
        outSteam.close();
        inStream.close();
        String result = new String(outSteam.toByteArray(),"utf-8");
        System.out.println(result);
        Map<String, String> map = WXPayUtil.xmlToMap(result);
        String result_code = map.get("result_code");
        if (result_code!=null && "SUCCESS".equals(result_code)) {//用户支付成功
            //修改订单状态
            WxbOrder order = new WxbOrder();
            order.setOrderId(map.get("out_trade_no"));
            order.setState(1);//状态 0：未支付 1：已支付 2：已关闭
            boolean b = iWxbOrderService.updateById(order);
        }
        Map res = new HashMap(){{
            put("return_code","SUCCESS");
            put("return_msg","OK");
        }};
        return WXPayUtil.mapToXml(res);
    }


    //查询订单状态的接口
    @RequestMapping("queryOrder")
    public  Result queryOrder(String orderId){
        return payService.queryOrderStatus(orderId);
    }




}